import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.utils import parseaddr, formataddr
from email.header import Header
import os
from os.path import join, getsize
import mimetypes

"""邮件发送"""
class EmailManager:
    def __init__(self, **params): # *以元组形式传参；**以字典形式传参
        self.msg_from = params['msg_from']
        self.password = params['password']
        self.msg_to = params['msg_to']
        self.msg_subject = params['msg_subject']
        self.msg_content = params['msg_content']
        self.msg_date = params['msg_date']
        self.attach_file = params['attach_file']
        self.smtp_server = 'smtp.163.com'
        self.MAX_FILE_SIZE = 10*1024*1024

    def login_server(self):
        server = smtplib.SMTP(self.smtp_server, 25)
        server.set_debuglevel(1)
        server.login(self.msg_from, self.password)
        return server

    def get_main_msg(self):
        msg = MIMEMultipart()
        msg.attach(MIMEText(self.msg_content, 'plain', 'utf-8'))
        msg['From'] = self._format_addr('From <%s>' % self.msg_from)
        msg['To'] = self._format_addr('To <%s>' % self.msg_to)
        msg['Subject'] = Header(self.msg_subject, 'utf-8')
        msg['Date'] = self.msg_date
        attach_file = self.get_attach_file()
        if attach_file is not None:
            msg.attach(attach_file)
        return msg
    def get_attach_file(self):
        if self.attach_file is not None and self.attach_file != '':
            try:
                if getsize(self.attach_file) > self.MAX_FILE_SIZE:
                    raise Exception('The attachment is too large and the upload failed!!')
                with open(self.attach_file, 'rb') as file:
                    ctype, encoding = mimetypes.guess_type(self.attach_file)
                    if ctype is None or encoding is not None:
                        ctype = 'application/octet-stream'

                    maintype, subtype = ctype.split('/', 1)

                    mime = MIMEBase(maintype, subtype)
                    mime.set_payload(file.read())
                    mime.add_header('Content-Disposition', 'attachment',
                                    filename=os.path.basename(self.attach_file))
                    mime.add_header('Content-ID', '<0>')
                    mime.add_header('X-Attachment-Id', '0')
                    encoders.encode_base64(mime)
                    return mime
            except Exception as e:
                print('%s......' % e)
                return None
        else:
            return None

    def _format_addr(self, s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    def send(self):
         try:
             server = self.login_server()
             msg = self.get_main_msg()
            #  server.sendmail(self.msg_from, self.msg_to.split(','), msg.as_string())
            #  server.quit()
             print("Send succeed!!")
         except smtplib.SMTPException:
             print("Error:Can't send this email!!")

if __name__ == '__main__':
    mail_cfgs = {'msg_from': '18736199128@163.com',
        'password': '123',
        'msg_to':  'yanyan.shen@ht-med.com,emilyyanshen@163.com',
        'msg_subject': 'Python Auto Send Email Test',
        'msg_content': 'Hi, boy! Just do it, python!',
        'attach_file': r'/var/www/html/python/app/lib/test.txt',
        'msg_date': time.ctime()
        }
    manager = EmailManager(**mail_cfgs)
    manager.send()
